//
//  PersonInfoController.m
//  FD
//
//  Created by Yasin on 2018/10/17.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//

#import "PersonInfoController.h"
//view-cell
#import "BRInfoCell.h"
#import "BRInfoAvatorCell.h"

//veiw
#import "BRPickerView.h"
#import "BRTagView.h" //我的标签

//controller
#import "FamilyMemberBirthdayViewController.h"
#import "MyLabelViewController.h" //偏好标签页面
#import "TZImagePickerController.h" //图片选择器
#import <MobileCoreServices/MobileCoreServices.h>



@interface PersonInfoController ()<UITableViewDataSource,UITableViewDelegate,
UITextFieldDelegate,
BRInfoAvatorCellDelegate,
TZImagePickerControllerDelegate,
UINavigationControllerDelegate,
TZImagePickerControllerDelegate,
UINavigationControllerDelegate>

/**tableView*/
@property (nonatomic,  strong) UITableView *tv1;
/**数据源*/
@property (nonatomic,  strong) NSArray *titleArr;

/**我的标签*/
@property (nonatomic,  strong) BRTagView *tagView;

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@end

@implementation PersonInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupView];
    
    //请求数据
    [self loadData];
}

- (void)setupView {
    self.navigationItem.title = @"个人资料";
    self.view.backgroundColor = [UIColor whiteColor];

    self.tv1.frame = self.view.bounds;
    [self.view addSubview:self.tv1];
    
    //表尾
    self.tv1.tableFooterView = self.tagView;
    
}

- (NSArray *)titleArr {
    if (!_titleArr) {
        _titleArr = @[@"昵称",@"手机号",@"性别",@"生日",@"家庭成员生日"];
    }
    return _titleArr;
}

- (BRTagView *)tagView {
    if (!_tagView) {
        _tagView = [[BRTagView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    }
    return _tagView;
}

- (UITableView *)tv1 {
    if (!_tv1) {
        _tv1 = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tv1.delegate = self;
        _tv1.dataSource = self;
        
        //注册cell
        [_tv1 registerClass:[BRInfoCell class] forCellReuseIdentifier:@"BRInfoCell"]; //头像
        [_tv1 registerClass:[BRInfoAvatorCell class] forCellReuseIdentifier:@"BRInfoAvatorCell"];
        [_tv1 registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"]; //系统
    }
    return _tv1;
}


#pragma mark - 代理 UITableViewDataSource,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) { //头像cell
        BRInfoAvatorCell *avatorCell = [tableView dequeueReusableCellWithIdentifier:@"BRInfoAvatorCell"];
        avatorCell.delegate = self;
        return avatorCell;
    }else {
        BRInfoCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"BRInfoCell"];
        cell2.titleLabel.text = self.titleArr[indexPath.row];
        cell2.textField.tag = indexPath.row; //添加tag值,后面控制是否弹出键盘
        
        cell2.textField.delegate = self; //统一设置代理
        if (indexPath.row == 1) {
            cell2.textField.placeholder = @"请填写手机号"; //输入文字，其他的都是弹框
        }else if (indexPath.row == 2) {
            cell2.textField.placeholder = @"请选择性别";
        }else if (indexPath.row == 3) {
            cell2.textField.placeholder = @"请选择生日";
        }else if(indexPath.row == 4){
            cell2.textField.placeholder = @"请选择生日";
        }
        return cell2;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 60;
    }else{
        return 44;
    }
}

#pragma mark - 点击跳转到我的标签
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//        MyLabelViewController *labelLb = [MyLabelViewController new];
//        [self.navigationController pushViewController:labelLb animated:YES];
//}

#pragma mark - 代理 UITableViewDelegate

#pragma mark - 代理 UITextFieldDelegate

//填写姓名可以输入文字，其他的都是弹框
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 1) {
        [textField resignFirstResponder];
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.tag == 1) { //填写姓名可以输入文字，其他的都是弹框
        [textField addTarget:self action:@selector(handlerTextFieldEndEdit:) forControlEvents:(UIControlEventTouchUpInside)];
        return YES;
    }else {
        [self.view endEditing:YES];
        [self handlerTextFieldSelect:textField];
        return NO;
    }
}

- (void)handlerTextFieldEndEdit:(UITextField *)textField
{
    
}
- (void)handlerTextFieldSelect:(UITextField *)textField
{
    //弹框
    if (textField.tag == 2) { //选择性别
        [BRStringPickerView showStringPickerWithTitle:@"宝宝性别" dataSource:@[@"男", @"女", @"其他"] defaultSelValue:textField.text resultBlock:^(id selectValue) {
            //        textField.text = self.infoModel.genderStr = selectValue;
            textField.text = selectValue;
        }];
    }else if(textField.tag == 3) { //选择出生日期
        NSDate *minDate = [NSDate br_setYear:1990 month:3 day:12];
        NSDate *maxDate = [NSDate date];
        [BRDatePickerView showDatePickerWithTitle:@"出生日期" dateType:BRDatePickerModeYMD defaultSelValue:textField.text minDate:minDate maxDate:maxDate isAutoSelect:YES themeColor:nil resultBlock:^(NSString *selectValue) {
//            textField.text = self.infoModel.birthdayStr = selectValue;
            textField.text = selectValue;
        } cancelBlock:^{
            NSLog(@"点击了背景或取消按钮");
        }];
    }else if (textField.tag == 4) { //跳转到家庭成员生日页面
        [JRToast showWithText:@"跳转到家庭成员生日页面"];
        
        FamilyMemberBirthdayViewController *birthdayVC = [[FamilyMemberBirthdayViewController alloc] init];
        [self.navigationController pushViewController:birthdayVC animated:YES];
    }
}

//回收键盘
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}
#pragma mark - 头像点击
- (void)brInfoAvatorCellDidClockAvaorAction:(UIImageView *)iv
{
    NSLog(@"当前线程:%@",[NSThread currentThread]);
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *paiZhao = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self pushImagePickerController];
    }];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从相册选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self takePhoto];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    [alertVC addAction:paiZhao];
    [alertVC addAction:photoAction];
    [alertVC addAction:cancelAction];
    
    //
    [self presentViewController:alertVC animated:YES completion:nil];
}



#pragma mark - 请求数据
- (void)loadData {
    [FDHttpAPi requestUserPersonMsgSuccessBlock:^(id responseObjc) {
        NSLog(@"用户个人信息：%@",responseObjc);
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) { //请求成功解析数据
            
        }else { //toast
            [JRToast showWithText:responseObjc[describe]];
        }
        
    } failBlock:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

#pragma mark - fjafj
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}

#pragma mark - 图片选择器 三方
#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        [self permissionAlert];
        
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        [self permissionAlert];
        
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

//权限弹框
- (void)permissionAlert {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    [alertVc addAction:cancel];
    [self presentViewController:alertVc animated:YES completion:nil];
}


// 调用相机
- (void)pushImagePickerController {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];
        
        [mediaTypes addObject:(NSString *)kUTTypeImage];
        
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        [JRToast showWithText:@"模拟器中无法打开照相机,请在真机中使用"];
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}


- (void)pushTZImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        NSLog(@"111111111111111");
        //跳转滤镜控制器
        
        UIImage *img = [photos firstObject];
    }];
    
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

@end
